﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace Core
{
    public class ImageDropShadow
    {
        /// <summary>
        /// Draws a shadow on the image
        /// </summary>
        /// <param name="sourceImage">Image object which will have the shadow.</param>
        /// <param name="destination">The path where the image will be saved.</param>
        public static void Draw(Image sourceImage, string destination)
        {
            const int ALPHA = 170;
            const int SPREAD = 4;
            const int DISTANCE = 6;

            Graphics g = null;
            Bitmap shadowImg = null;
            Bitmap outputImg = null;
            try
            {
                // calculates the shadow size. The rectangle is smaller than image but when resized creates a blurred image
                int shadowWidth = Convert.ToInt32(sourceImage.Width / SPREAD);
                int shadowHeight = Convert.ToInt32(sourceImage.Height / SPREAD);

                shadowImg = new Bitmap(shadowWidth, shadowHeight);
                g = Graphics.FromImage(shadowImg);
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.FillRectangle(new SolidBrush(Color.FromArgb(ALPHA, Color.Black)), 1, 1, shadowWidth, shadowHeight);
			
                int outputWidth = sourceImage.Width + DISTANCE;
                int outputHeight = sourceImage.Height + DISTANCE;

                outputImg = new Bitmap(outputWidth, outputHeight);
                g = Graphics.FromImage(outputImg);
                g.Clear(Color.White);

                g.DrawImage(shadowImg, new Rectangle(0, 0, outputWidth, outputHeight), 0, 0, shadowImg.Width, shadowImg.Height, GraphicsUnit.Pixel);

                g.DrawImage(sourceImage, new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), 0, 0, sourceImage.Width,
                            sourceImage.Height, GraphicsUnit.Pixel);

                outputImg.Save(destination);
            }
            finally
            {
                if (g != null) g.Dispose();
                if (shadowImg != null) shadowImg.Dispose();
                if (outputImg != null) outputImg.Dispose();
            }
        }
    }
}